package com.lws.hellojmeter.db.controller;

import com.lws.hellojmeter.db.bean.DBInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/db.do")
public class DBController {

    private static final Map<String, DBInfo> DBINFOS = new HashMap<String, DBInfo>();
    private static final ServletFileUpload UPLOAD;

    static {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        UPLOAD = new ServletFileUpload(factory);
    }

    @RequestMapping(params = "method=addDB")
    public String addDB(HttpServletRequest request) throws ServletException, IOException {
        List<FileItem> items = null;
        try {
            items = UPLOAD.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        DBInfo dbInfo = new DBInfo();
        for (FileItem fileItem : items) {
            if (fileItem.isFormField()) {
                try {
                    Field field = dbInfo.getClass().getDeclaredField(fileItem.getFieldName());
                    field.setAccessible(true);
                    field.set(dbInfo, fileItem.getString());
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } else {
                StringBuilder dbScript = new StringBuilder();
                BufferedInputStream in = new BufferedInputStream(fileItem.getInputStream());
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) != -1) {
                    dbScript.append(new String(buf, 0, len));
                }
                in.close();
                dbInfo.setDbScript(dbScript.toString());
            }
        }
        DBINFOS.put(dbInfo.getDbName(), dbInfo);
        return "dbtest";
    }

    @ResponseBody
    @RequestMapping(params = "method=getAllDBs")
    public Map<String, DBInfo> getAllDBs() {
        return DBINFOS;
    }

}
